<template>
  <div>
    <!-- 查询窗口 -->
    <el-form
      ref="queryForm"
      :model="queryParams"
      class="form"
    >
      <el-row :gutter="20">
        <el-col :span="7.5">
          <el-form-item
            size="small"
            prop="name"
            label-width="80px"
          >
            <label
              slot="label"
            >{{$t('product_category_category_9')}}</label>
            <el-input
              v-model="queryParams.name"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item
            :label="$t('product_category_category_10')"
            size="small"
            prop="createTime"
            label-width="80px"
            style="margin-left: 45px"
          >
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-:separator="$t('product_category_category_11')"
              start-:placeholder="$t('product_category_category_12')"
              end-:placeholder="$t('product_category_category_13')"
              style="margin-right: 40px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item
            :label="$t('product_category_category_14')"
            size="small"
            prop="isParent"
            label-width="80px"
          >
            <el-select
              v-model="queryParams.isParent"
              :placeholder="$t('product_category_category_15')"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item size="small">
            <el-button
              v-hasAuthority="['product:category:list']"
              type="primary"
              class="query"
              @click="handleQuery"
            >{{$t('product_category_category_16')}}</el-button>
            <el-button
              v-hasAuthority="['product:category:list']"
              type="primary"
              style="width: 60px; margin-left: 40px"
              @click="resetQuery"
            >{{$t('product_category_category_17')}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="20">
      <el-col :span="10">
        <el-button
          v-hasRole="['admin','purchaser']"
          type="danger"
          :disabled="multiple"
          class="deletes"
          @click="handleDelete"
        >{{$t('product_category_category_18')}}</el-button>
        <el-button
          v-hasRole="['admin','purchaser']"
          class="insertButton"
          @click="handleAdd"
        >{{$t('product_category_category_19')}}</el-button>
      </el-col>
    </el-row>
    <!-- 数据展示Table -->
    <el-table
      v-loading="loading"
      border
      :data="dataList"
      style="border: 1px solid rgb(211 211 211); margin-left: 20px; width: 96%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
      />
      <el-table-column
        v-if="false"
        label="ID"
        prop="id"
      />
      <el-table-column
        :label="$t('product_category_category_9')"
        align="center"
        prop="categoryName"
      />
      <el-table-column
        :label="$t('product_category_category_20')"
        align="center"
      >
        <template slot-scope="scope">
          <img
            v-if="scope.row.imageUrl != null"
            :src="scope.row.imageUrl"
            alt="Category Image"
            style="width: 120px; height: auto"
          >
          <span v-else>{{$t('product_category_category_21')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('product_category_category_22')"
        align="center"
        prop="isParent"
        width="150"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.isParent == 1">{{$t('product_category_category_23')}}</span>
          <span v-else>{{$t('product_category_category_24')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('product_category_category_10')"
        align="center"
        prop="createTimeString"
      />
      <el-table-column
        :label="$t('product_category_category_25')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasRole="['admin','purchaser']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{$t('product_category_category_26')}}</el-button>
          <el-button
            v-hasRole="['admin','purchaser']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >{{$t('product_category_category_27')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页加载 -->
    <el-pagination
      :current-page="showAllParams.current"
      :page-sizes="[5, 10, 20]"
      :page-size="showAllParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新增弹窗，默认不显示 -->
    <el-dialog
      :title="$t('product_category_category_19')"
      :visible.sync="insertOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          :label="$t('product_category_category_9')"
          prop="name"
        >
          <el-input
            v-model="form.name"
            :placeholder="$t('product_category_category_28')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('product_category_category_20')"
          prop=""
        >
          <el-upload
            ref="upload1"
            v-hasRole="['admin','purchaser']"
            class="upload-demo"
            action="http://localhost:8101/file/upload"
            :on-change="handleFileChange"
            :on-remove="handleRemoveImage"
            :limit="1"
            :auto-upload="false"
          >
            <el-button
              slot="trigger"
              size="small"
              type="primary"
            >{{$t('product_category_category_29')}}</el-button>
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="upload"
            >{{$t('product_category_category_30')}}</el-button>
            <div
              slot="tip"
              class="el-upload__tip"
            >{{$t('product_category_category_31')}}</div>
            <i
              v-if="uploadSuccess"
              class="el-icon-success"
            />
          </el-upload>
        </el-form-item>
        <el-form-item
          :label="$t('product_category_category_22')"
          prop="isParent"
        >
          <el-radio
            v-model="form.isParent"
            label="1"
          >{{$t('product_category_category_23')}}</el-radio>
          <el-radio
            v-model="form.isParent"
            label="0"
          >{{$t('product_category_category_24')}}</el-radio>
        </el-form-item>
        <!-- 当一级分类等于 $t('product_category_category_24') 时显示 -->
        <el-form-item
          v-if="form.isParent === '0'"
          :label="$t('product_category_category_32')"
          prop="parentId"
        >
          <el-select
            v-model="form.parentId"
            :placeholder="$t('product_category_category_15')"
          >
            <el-option
              v-for="item in chooseParentOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          v-hasRole="['admin','purchaser']"
          type="primary"
          @click="submitInsertForm"
        >{{$t('product_category_category_33')}}</el-button>
        <el-button @click="cancel">{{$t('product_category_category_34')}}</el-button>
      </div>
    </el-dialog>
    <!-- 修改弹窗，默认不显示 -->
    <el-dialog
      :title="$t('product_category_category_35')"
      :visible.sync="updateOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          v-if="false"
          label="ID"
          prop="id"
        >
          <el-input
            v-model="form.id"
            placeholder="ID"
          />
        </el-form-item>
        <el-form-item
          :label="$t('product_category_category_9')"
          prop="name"
        >
          <el-input
            v-model="form.name"
            :placeholder="$t('product_category_category_28')"
          />
        </el-form-item>
        <el-form-item
          v-if="form.isParent === '0'"
          :label="$t('product_category_category_36')"
          prop="parentId"
        >
          <el-select
            v-model="form.parentId"
            :placeholder="$t('product_category_category_15')"
          >
            <el-option
              v-for="item in chooseParentOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('product_category_category_20')"
          prop="imageUrl"
        >
          <el-upload
            ref="upload2"
            v-hasRole="['admin','purchaser']"
            class="upload-demo"
            action="http://localhost:8101/file/upload"
            :on-change="handleFileChange"
            :on-remove="handleRemoveImage"
            :limit="1"
            :auto-upload="false"
          >
            <el-button
              slot="trigger"
              size="small"
              type="primary"
            >{{$t('product_category_category_29')}}</el-button>
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="upload"
            >{{$t('product_category_category_30')}}</el-button>
            <div
              slot="tip"
              class="el-upload__tip"
            >{{$t('product_category_category_31')}}</div>
            <i
              v-if="uploadSuccess"
              class="el-icon-success"
            />
          </el-upload>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          v-hasRole="['admin','purchaser']"
          type="primary"
          @click="submitUpdateForm"
        >{{$t('product_category_category_33')}}</el-button>
        <el-button @click="cancel">{{$t('product_category_category_34')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  updateCategory,
  listAll,
  listAllParent,
  getCategory,
  delCategory,
  delCategorys,
  addCategory,
  uploadFile,
} from "@/api/category";
import { mapGetters } from 'vuex';
export default {
  data() {
    return {
      // 上传文件
      uploadFileRequest: {
        biz: "category",
      },
      // 遮罩层
      loading: false,
      radio: "1",
      // 表格数据
      dataList: [],
      // 展示所有类别参数
      showAllParams: {
        current: 1,
        pageSize: 10,
        sortField: null,
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: "",
        isParent: "",
        startTime: " ",
        endTime: " ",
      },
      createTime: [],
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 下拉框选项数据
      parentOptions: [
        {
          value: "1",
          label: this.$t('product_category_category_22'),
        },
        {
          value: "2",
          label: this.$t('product_category_category_37'),
        },
      ],
      // 勾选1个或多个
      multiple: true,
      // 是否显示弹出层
      insertOpen: false,
      updateOpen: false,
      // 表单
      form: {
        name: "",
        isParent: "1",
        parentId: 1,
        imageUrl: "",
      },
      chooseParentOptions: [],
      // 用来保存选中的文件
      selectedFile: null,
      //文件是否上传成功
      uploadSuccess: false,
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: this.$t('product_category_category_38'), trigger: "blur" },
        ],
      },
    };
  },    
  computed: {
    ...mapGetters([
      'roles',
    ])
  },
  created() {
    this.getAll();
    this.getParentOptions();
  },
  methods: {
    // 展示所有数据
    getAll() {
      this.loading = true;
      listAll(this.showAllParams).then((response) => {
        this.dataList = response.data.records;
        this.total = Number(response.data.total);
        this.loading = false;
        this.imageUrl = response.data.imageUrl;
      });
    },
    // 查询数据列表
    getList() {
      this.loading = true;
      listAll(this.queryParams).then((response) => {
        this.dataList = response.data.records;
        this.total = Number(response.data.total);
        this.loading = false;
        this.imageUrl = response.data.imageUrl;
      });
    },
    /** 查询所有父級 */
    getParentOptions() {
      listAllParent().then((response) => {
        this.chooseParentOptions = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.loading = true;
      this.queryParams.startTime = this.createTime[0];
      this.queryParams.endTime = this.createTime[1];
      // console.log(this.queryParams)
      getCategory(this.queryParams).then((response) => {
        this.dataList = response.data.records;
        this.total = +response.data.total;
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.createTime = "";
      this.getList();
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.resetForm();
      if (row.isParent == 0) {
        this.form.isParent = "0";
      }
      this.form.name = row.categoryName;
      this.form.id = row.id;
      this.form.parentId=row.parentId;
      this.updateOpen = true;
    },
    /** 编辑提交按钮 */
    submitUpdateForm: function () {
      // console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateCategory(this.form).then((msg) => {
            this.$message.success(msg);
            this.getList();
            this.cancel();
          });
        }
      });
    },
    // 新增按钮操作
    handleAdd() {
      this.resetForm();
      this.getParentOptions();
      this.insertOpen = true;
    },
    /** 新增提交按钮 */
    submitInsertForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addCategory(this.form).then((msg) => {
            this.$message.success(msg);
            this.getList();
            this.cancel();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const categoryName = row.categoryName || this.names;
      this.$confirm(
        '是否确认删除名称为"' + categoryName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // eslint-disable-next-line brace-style
          // console.log(row.id);
          // eslint-disable-next-line brace-style
          if (Array.isArray(this.ids) && this.ids.length > 1) {
            return delCategorys(this.ids);
          }
          // 执行单个删除
          else {
            return delCategory(row.id);
          }
        })
        .then((response) => {
          this.getList(); // 刷新数据
          this.$message.success(response.message);
        })
        .catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.names = selection.map((item) => item.categoryName);
      this.single = selection.length !== 1;
      this.multiple = !(selection.length>=1);
      // console.log(this.ids);
    },
    /** 表单初始化 */
    resetForm() {
      // 可进行数据初始化工作
      this.form = {
        id: null,
        name: null,
        isParent: "1",
      };
    },
    /** 取消按钮 */
    cancel() {
      this.insertOpen = false;
      this.updateOpen = false;
      this.resetForm();
      this.clear();
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    /**文件上传 */
      //检查文件格式
    beforeUpload(file) {
      // 允许的文件类型
      const allowedTypes = ["image/jpeg","image/jpg","image/svg+xml","image/png","image/webp"];
      // 文件大小限制为 1MB
      const isLt1M = file.size / 1024 / 1024 < 1;
      // 检查文件类型
      const isAllowedType = allowedTypes.includes(file.raw.type);
      // 如果文件类型不正确
      if (!isAllowedType) {
        this.$message.error( this.$t('product_category_category_39') );
      }
      // 如果文件大小超过 1MB
      else if (!isLt1M) {
        this.$message.error(this.$t('product_category_category_40'));
      }
      // 返回是否通过验证
      return isAllowedType && isLt1M;
    },
    //接收文件列表
    handleFileChange(file, fileList) {
      if(!this.beforeUpload(file)){
        fileList.splice(0,1)
      }
      else
        // fileList 是一个文件列表，但因为限制了只能上传一个文件，所以只取第一个
        this.selectedFile = fileList[0];
    },
    //移除文件时检查文件列表
    handleRemoveImage(file, fileList) {
      if (fileList.length == 0) {
        this.uploadSuccess = false;
      }
    },
    async upload() {
      try {
        const response = await uploadFile(
          this.selectedFile.raw,
          this.uploadFileRequest
        );
        this.form.imageUrl = response.data;
        // console.log(this.$t('product_category_category_41'), response.data);
        this.$message({
          message: this.$t('product_category_category_41'),
          type: "success",
        });
        this.uploadSuccess = true;
      } catch (error) {
        console.error(this.$t('product_category_category_42'), error);
        this.$message.error(this.$t('product_category_category_43'));
      }
    },
    //清除文件上传信息
    clear() {
      // 用来保存选中的文件
      this.selectedFile = null;
      //文件是否上传成功
      this.uploadSuccess = false;
      this.$refs.upload1.fileList = [];
      this.$refs.upload2.fileList = [];
      // console.log(this.$refs.upload.fileList);
    },
  },
};
</script>
<style scoped>
.form {
  border: 2px dashed rgb(211, 211, 211);
  padding: 20px;
  padding-bottom: 0px;
  margin: 10px 20px 20px 20px;
}
.deletes {
  width: 130px;
  margin-left: 20px;
  margin-bottom: 10px;
}
.query {
  margin-left: 30px;
  width: 60px;
}
.avatar-uploader-icon .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-right: 10px;
}
.avatar {
  width: 100px;
  height: 100px;
  display: inline;
}
.insertButton,
.insertButton:hover {
  background-color: #4ac1cd;
  color: white;
  width: 130px;
}
.insertButton:hover {
  background-color: #90ccd2;
}
.page {
  margin-top: 5px;
  margin-left: 280px;
}
.el-icon-success {
  margin-left: 20px;
  font-size: 20px;
  color: green;
}
</style>
